package cn.bugstack.openai.executor.model.baidu.utils;

import cn.bugstack.openai.executor.model.baidu.config.BaiduConfig;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import okhttp3.*;

import java.util.concurrent.TimeUnit;

public class AccessTokenUtils {

    private AccessTokenUtils() {
    }
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(AccessTokenUtils.class);

    // 过期时间；默认60分钟
    private static final int EXPIRE_MILLIS = 60 * 60 * 1000;
    // 缓存服务
    public static Cache<String, String> cache = CacheBuilder.newBuilder()
            .expireAfterWrite(EXPIRE_MILLIS - (60L * 1000L), TimeUnit.MINUTES)
            .build();

    public static String getAccessToken(String apiKey, String apiSecret) {
        try {
            // 缓存Token
            String token = cache.getIfPresent("accessToken");
            if (null != token)
                return token;
            Request request = new Request.Builder()
                    .url(BaiduConfig.AUTH_HOST)
                    .post(RequestBody.create("grant_type=client_credentials&client_id=" + apiKey + "&client_secret=" + apiSecret
                            , MediaType.parse("application/x-www-form-urlencoded")))
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .build();
            try (Response response = new OkHttpClient().newBuilder().build().newCall(request).execute()) {
                if (response.isSuccessful() && response.body() != null) {
                    JSONObject jsonObject = JSONUtil.parseObj(response.body().string());
                    token = jsonObject.getStr("access_token");
                    cache.put("accessToken", token);
                }
            }
            return token;
        } catch (Exception e) {
            LOGGER.message("获取百度Token失败").exception(e).error();
        }
        return null;
    }
}